package fr.ordre66.vlcs.client;

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import fr.ordre66.vlcs.utils.VlcsHttpClient;

public class SendImageThread extends Thread {

	IHM ihm;
	boolean motionActive = false;

	public SendImageThread(IHM ihm) {
		this.ihm = ihm;
	}

	public void run() {

			for (;;) {
				try {

					TimeOutThread t = new TimeOutThread(this);
					t.run();
					String path = "/tmp/image.jpeg";
					File file = new File(path);					
					long oldImgSize = file.length();

					
					ImageIO.write(ihm.getImage(), "jpeg", file);
					long lastImgSize = file.length();
					
					long diff = Math.abs((lastImgSize - oldImgSize));
					//motion detection
					if(diff > 1000 && motionActive){
						
						System.out.println("Motion capture: " + diff);
						ihm.getPlayer().playSong();
						
						SendVideoThread svThread = new SendVideoThread(ihm);
						svThread.run();
					}
						
						
					VlcsHttpClient httpClient = new VlcsHttpClient();
					httpClient.sendData(path, "img", ihm.getConfigFrame().getLogin(), ihm.getConfigFrame().getPassword());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
	}
	
	
	
	public void setMotionActive(boolean motionActive) {
		this.motionActive = motionActive;
	}



	public class TimeOutThread extends Thread {
		
		SendImageThread s;
		
		public TimeOutThread(SendImageThread s){
			this.s = s;			
		}
		public void run() {
			
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			s.setMotionActive(true);
		}
		
	}
}
